package com.clark.crawler.novel;

import com.clark.crawler.novel.bean.Chapter;
import com.clark.crawler.novel.property.NovelPropertyUtil;
import com.clark.crawler.util.FileUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:
 *
 * @author tianhua.xie（tianhua.xie@ucarinc.com）
 * @version 1.0
 * @date 2018/12/26 14:39
 */
public class NovelUtil {
    private static List<String> chapterList;
    private static Map<String,Chapter> chapterMap = new HashMap<String, Chapter>();
    private static Integer chapterCnt = -1;

    public static void init(List<String> chapterList) {
        if (chapterList == null){
            return;
        }
        NovelUtil.chapterList = new ArrayList<String>();
        for (String url :chapterList) {
            if (url == null || NovelUtil.chapterList.contains(url)) {
                continue;
            }
            NovelUtil.chapterList.add(url);
        }
        NovelUtil.chapterCnt =  NovelUtil.chapterList.size();
    }

    public static void addChapter(Chapter chapter) {
        chapterMap.put(chapter.getUrl(),chapter);
        if (chapterMap.size() >= chapterList.size()) {
            save();
        }
    }

    public static void save(){
        String path = NovelPropertyUtil.getFilePath();
        String separator = System.getProperty("line.separator");

        for (String cha : chapterList) {
            StringBuffer contentSB = new StringBuffer();
            Chapter chapter = chapterMap.get(cha);
            try {
                contentSB.append(chapter.getTitle()).append(separator)
                        .append(chapter.getContent())
                        .append(separator).append(separator).append(separator).append(separator);
                FileUtil.appendFileContext(path,contentSB.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
